import React, {
  createContext,
  useState,
  useContext,
  useEffect,
  ReactNode,
} from "react";
import { Appearance, ColorSchemeName, useColorScheme } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { lightTheme, darkTheme } from "@/styles/theme.style";
import { ThemeProvider as RNEUIThemeProvider } from "@rneui/themed";
import { getRNEUITheme } from "@/theme/rneui-theme";

// 主题模式类型
export type ThemeMode = "light" | "dark" | "system";

// 主题上下文类型
interface ThemeContextType {
  themeMode: ThemeMode;
  activeTheme: "light" | "dark"; // 当前实际应用的主题
  setThemeMode: (mode: ThemeMode) => void;
  toggleTheme: () => void;
  colors: typeof lightTheme; // 当前主题的颜色对象
}

// 创建主题上下文
const ThemeContext = createContext<ThemeContextType>({
  themeMode: "system",
  activeTheme: "light",
  setThemeMode: () => {},
  toggleTheme: () => {},
  colors: lightTheme,
});

const THEME_STORAGE_KEY = "@app_theme_mode";

/**
 * 主题提供者组件
 *
 * 管理应用的主题状态（深色/浅色模式）
 */
export const ThemeProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  const [themeMode, setThemeModeState] = useState<ThemeMode>("system");
  const systemTheme = useColorScheme();
  const [systemThemeOverride, setSystemThemeOverride] =
    useState<ColorSchemeName>(null);

  // 监听系统主题变化
  useEffect(() => {
    const subscription = Appearance.addChangeListener(({ colorScheme }) => {
      setSystemThemeOverride(colorScheme);
    });

    return () => {
      subscription.remove();
    };
  }, []);

  // 获取当前实际应用的主题
  const activeTheme =
    themeMode === "system"
      ? (systemThemeOverride || systemTheme) === "dark"
        ? "dark"
        : "light"
      : themeMode === "dark"
      ? "dark"
      : "light";

  // 获取当前主题的颜色
  const colors = activeTheme === "dark" ? darkTheme : lightTheme;

  // 获取 RNEUI 主题
  const rneuiTheme = getRNEUITheme(activeTheme === "dark");

  // 初始化：从存储中加载主题设置
  useEffect(() => {
    const loadThemeMode = async () => {
      try {
        const savedThemeMode = await AsyncStorage.getItem(THEME_STORAGE_KEY);
        if (savedThemeMode) {
          setThemeModeState(savedThemeMode as ThemeMode);
        }
      } catch (error) {
        console.error("Failed to load theme mode:", error);
      }
    };

    loadThemeMode();
  }, []);

  // 持久化保存主题设置
  const setThemeMode = async (mode: ThemeMode) => {
    try {
      await AsyncStorage.setItem(THEME_STORAGE_KEY, mode);
      setThemeModeState(mode);
    } catch (error) {
      console.error("Failed to save theme mode:", error);
    }
  };

  // 切换主题
  const toggleTheme = () => {
    const nextTheme = activeTheme === "light" ? "dark" : "light";
    setThemeMode(nextTheme);
  };

  return (
    <ThemeContext.Provider
      value={{
        themeMode,
        activeTheme,
        setThemeMode,
        toggleTheme,
        colors,
      }}
    >
      <RNEUIThemeProvider theme={rneuiTheme}>{children}</RNEUIThemeProvider>
    </ThemeContext.Provider>
  );
};

/**
 * 使用主题的钩子
 *
 * 获取当前主题状态及相关方法
 */
export const useTheme = () => useContext(ThemeContext);
